#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

export PATH=$TOP_DIR/cross/bin:$PATH

VER_OPT=0.18.3.1

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d gettext-$VER_OPT ] ; then
		wget http://ftp.gnu.org/pub/gnu/gettext/gettext-$VER_OPT.tar.gz
		tar xzf gettext-$VER_OPT.tar.gz
	fi
	cd ..
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	HOST_FLAG="--host=x86_64-w64-mingw32"
	export CXX=x86_64-w64-mingw32-g++
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		HOST_FLAG="--host=i686-w64-mingw32"
		export CXX=i686-w64-mingw32-g++
	fi
#	export gl_cv_func_memchr=yes
	export gl_cv_func_memchr_works=yes
#	export ac_cv_func_strnlen=yes
	export ac_cv_func_strnlen_working=yes
	export ac_cv_func_snprintf=yes
	export ac_cv_func_vsnprintf=yes
#	export ac_cv_func_vasprintf=yes
	export gt_cv_func_printf_posix=yes
	rm -rf $BIN_DIR/gettext
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_gettext
	mkdir bd_gettext
	cd bd_gettext
	export CPPFLAGS="-D_POSIX=1 -I$BIN_DIR/mingw_dgn_lib/include -I$BIN_DIR/libiconv/include"
	export LDFLAGS="-L$BIN_DIR/mingw_dgn_lib/lib -L$BIN_DIR/libiconv/lib"
#	patch -d $SRC_DIR/gettext-$VER_OPT -p0 < $TOP_DIR/patch/gettext-0.18.x-w64.patch
	$SRC_DIR/gettext-$VER_OPT/configure $HOST_FLAG --prefix=$BIN_DIR/gettext \
			--enable-relocatable --enable-threads=win32 \
			--enable-shared --disable-static
		
# under mingw-w64, libiconv store files in lib, but gettext try to find it in lib64
#			--with-libiconv-prefix=$BIN_DIR/libiconv \

#	--enable-static --disable-shared
#	--enable-shared --disable-static
#	--disable-nls

	# FIXME : patch libtool before built if needed

	make $MAKE_OPT
	make install
#	patch -d $SRC_DIR/gettext-$VER_OPT -p0 -R < $TOP_DIR/patch/gettext-0.18.x-w64.patch
	cd ..
	cd ..
fi

